package com.greenet.companytemplate.security.handler;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Session Timeout Handler for XMLHttpRequest
 * Response: 401
 * Created by brett on 2015/12/2.
 */
public class SessionTimeoutHandler extends LoginUrlAuthenticationEntryPoint {

    public SessionTimeoutHandler(String loginFormUrl) {
        super(loginFormUrl);
    }

    /**
     * send error code 401 for XMLHttpRequest
     * @param request
     * @param response
     * @param authException
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {

        if ( "XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With")) && authException != null) {
            //response.sendError(HttpServletResponse.SC_UNAUTHORIZED);//跳转到web.xml中的错误页面
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);//只含有header, 其中Content-Length:0
        }
        else {
            super.commence(request, response, authException);
        }
    }
}
